package com.ls.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.entity.Customer;
import com.ls.entity.SmsRecord;
import com.ls.enums.SmsStatusEnum;
import com.ls.service.ICustomerService;
import com.ls.service.ISmsRecordService;
import com.ls.utils.ResultData;
import com.ls.utils.sms.SmsPyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import static com.ls.constant.SystemConstants.NUMBER_0;
import static com.ls.constant.SystemConstants.SMS_STATUS_SENDING;

/**
 * 获取短信状态轮询
 */
@Slf4j
@Component
public class SmsStatusTask {
    @Autowired
    private ISmsRecordService smsRecordService;
    @Autowired
    private ICustomerService customerService;

    @Scheduled(cron = "${schedule.sms.cron}")
    private void getSmsStatus() {
        List<SmsRecord> smsRecordList = smsRecordService.list(new LambdaQueryWrapper<SmsRecord>()
                .eq(SmsRecord::getSmsStatus, SMS_STATUS_SENDING)
                .le(SmsRecord::getCreateTime, LocalDateTime.now().minusSeconds(30))
        );
        if (smsRecordList == null || smsRecordList.size() == 0 || smsRecordList.isEmpty()) {
            return;
        }
        smsRecordList.forEach(smsRecord -> {
            try {
                SmsRecord record = smsRecordService.getById(smsRecord.getSmsRecordId());
                ResultData result = SmsPyUtil.getSmsStatus(smsRecord.getRecordId());
                if (result.isSuccess()) {
                    JSONObject data = (JSONObject) result.getData();
                    String returnCode = data.getString("returnCode");
                    Integer smsStatus = data.getInteger("smsStatus");
                    if (smsStatus == 0) {
                        smsStatus = 2;
                    }
                    if (smsStatus == 2 || smsStatus == 3) {
                        smsStatus = 3;
                    }
                    if (smsStatus == 1 || smsStatus == 3) {
                        record.setSmsStatus(smsStatus);
                        if (smsStatus == 1) {
                            record.setReturnCode(returnCode);
                            record.setReturnText(SmsStatusEnum.getReturnText(returnCode));
                            Customer customer = customerService.getById(record.getCustomerId());
                            if (record.getSmsSource() == 1) {
                                customer.setMessageNum(customer.getMessageNum() + record.getSmsReduceNum());
                            } else {
                                customer.setSmsThaliNum(customer.getSmsThaliNum() + record.getSmsReduceNum());
                            }
                            customer.setSmsTotal(customer.getSmsTotal() + record.getSmsReduceNum());
                            customer.setCurrentSendTimes(customer.getCurrentSendTimes() - 1);
                            customer.setPlatformSendTimes(customer.getPlatformSendTimes() - 1);
                            customer.setSendTimes(customer.getSendTimes() - 1);
                            customer.updateById();
                            log.info("更新用户信息短信条数：{}", JSON.toJSONString(customer));
                            record.setSmsReduceNum(NUMBER_0);
                        }
                        smsRecordService.updateById(record);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
